

package com.saas.ability.core.base.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleExecutorFactory implements ExecutorFactory {
	
	Logger logger = LoggerFactory.getLogger(SimpleExecutorFactory.class);
	
	ThreadPoolConfig config;
	
	public SimpleExecutorFactory(ThreadPoolConfig config){
		this.config = config;
	}
	
	protected Executor get(String name,ThreadPoolConfig config) {
        int corePoolSize = config.getCorePoolSize();
        int maxPoolSize = config.getMaxPoolSize();
        int keepAliveSeconds = config.getKeepAliveSeconds();
        BlockingQueue<Runnable> queue = config.getQueue();

        return new DefaultExecutor(corePoolSize
                , maxPoolSize
                , keepAliveSeconds
                , TimeUnit.SECONDS
                , queue
                , new NamedPoolThreadFactory(name)
                , new DumpThreadRejectedHandler(name,config));
    }

    @Override
    public Executor get(String name,String executorType) {
        switch (name) {
            case EVENT_BUS:
            	return get(name,config);
             default: {
            	 if(EXECUTOR_TYPE.equals(executorType)){
            		 int corePoolSize = Runtime.getRuntime().availableProcessors();
            		 ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize,
                             new NamedPoolThreadFactory(name),
                             (r, e) -> logger.error("one ack context was rejected, context=" + r)
                     );
                     executor.setRemoveOnCancelPolicy(true);
                     return executor;
            	 }else{
            		 return get(name,config);
            	 }
            }
        }
    }
}
